package com.example.zuulfileupload.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by smlz on 2019/4/24.   spring的文件上传
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileUploadController {

    @Autowired
    private Environment env;

    @RequestMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file) throws IOException {
        log.info("上传的文件名称:{}", file.getOriginalFilename());
        log.info("文件上传的大小:{}", file.getSize());

        String fileName = file.getOriginalFilename();
        //文件后缀名
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);

        //根据当前时间来创建文件名
        String time = Long.toString(System.currentTimeMillis());

        StringBuilder sb = new StringBuilder();
        sb.append(System.getProperty("user.dir"))
                .append(File.separator)
                .append("upload")
                .append(File.separator)
                .append(time)
                .append(".")
                .append(prefix);

        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("/upload")
                .append("/")
                .append("upload")
                .append("/")
                .append(time)
                .append(".")
                .append(prefix);

        File tempFile = new File(sb.toString());
        try {
            File targetFile = new File(tempFile.toString());
            if (targetFile.exists()) {
                return "文件已存在";
            }

            if (!targetFile.getParentFile().exists()) {
                targetFile.getParentFile().mkdirs();
            }
            file.transferTo(targetFile);

            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }

//        String path = ":" ;
//        File dest = new File(path + "/" + file.getOriginalFilename());
//        if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
//            dest.getParentFile().mkdir();
//        }
//        try {
//            file.transferTo(dest); //保存文件
//            return "true";
//        } catch (IllegalStateException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//            return "false";
//        } catch (IOException e) {
//            // TODO Auto-generated catch block
//            e.printStackTrace();
//            return "false";
//        }

    }
}
